﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.AspNet.SignalR;

namespace TestSignalrService
{
    public class MyHub : Hub
    {
        public void Send(string name, string message)
        {
            //像所有连接的用户发送消息
            var user = DataManager.Instance.GetUser(Context.ConnectionId);
            if(user!=null)
            {
                Clients.All.addMessage(new MessageItem(message,user.Nick,user.ConnectedId));
            }
            
        }
        /// <summary>
        /// 发送私聊消息
        /// </summary>
        /// <param name="msg"></param>
        /// <param name="toCid"></param>
        public void SendTo(string msg, string toCid)
        { 
            var fromUser = DataManager.Instance.GetUser(Context.ConnectionId);
            //检测用户是否在线，这里就不写了
            Clients.Client(toCid).ReceiveMsg(new MessageItem(msg,fromUser.Nick,fromUser.ConnectedId));
        }

        /// <summary>
        /// 相当于登录验证吧
        /// </summary>
        /// <param name="username"></param>
        public void Vilidate(string username)
        {
            var result = DataManager.Instance.AddUser(new UserInfo(username, Context.ConnectionId));
            if (result)
            {
                //系统消息
                Clients.All.addMessage_system(string.Format("欢迎{0}加入聊天.", username));
                Clients.All.NotciceUserCount(DataManager.Instance.CurrentUserList.Count);
            }
            else
            {
                Clients.Client(Context.ConnectionId).Receive("进入失败");
            }
        }

        //主动断开连接。退出,直接从在线用户的数据集合中去掉
        public void OutExsit()
        {
            if (DataManager.Instance.RemoveUser(Context.ConnectionId))
            {
                Clients.Client(Context.ConnectionId).Receive("您已经断开连接");
                Clients.All.NotciceUserCount(DataManager.Instance.CurrentUserList.Count);
            }
           
        }
        /// <summary>
        /// 用户链接进来的事件
        /// </summary>
        /// <returns></returns>
        public override Task OnConnected()
        {
            Console.WriteLine(string.Format("{0}连接到服务器!", Context.ConnectionId));
            //通知当前链接的用户连接成功
            //Clients.Client(Context.ConnectionId).Receive("链接服务器成功");
            return base.OnConnected();
        }
        /// <summary>
        /// 用户断开连接的事件
        /// </summary>
        /// <param name="stopCalled"></param>
        /// <returns></returns>
        public override Task OnDisconnected(bool stopCalled)
        {
            Console.WriteLine(string.Format("{0}断开服务器!", Context.ConnectionId));
            Clients.All.NotciceUserCount(DataManager.Instance.CurrentUserList.Count);
            if (DataManager.Instance.RemoveUser(Context.ConnectionId))
            {
                Clients.Client(Context.ConnectionId).Receive("您已经断开连接");
            }
            return base.OnDisconnected(stopCalled);
        }
    }
}
